/* 
 * File:   Mod.cpp
 * Author: Gab'z
 * 
 * Created on 3 juin 2012, 22:43
 */

#include "Mod.h"
#include "../../../Context.h"
#include "../../literal/Stack.h"
#include "../../literal/Complex.h"
#include "../../literal/Integer.h"

namespace calculator {

    Mod::Mod(const std::string name) : BinaryOperator(name) {
    }

    Mod::Mod(const Mod& orig) : BinaryOperator(orig._name) {
    }

    Mod::~Mod() {
    }

    std::string Mod::isExecutable() const {
        if (Context::getInstance()->getCurrentStack()->size() < 2) return "There must be at least 2 numbers in stack";
        const Integer* i1 = dynamic_cast<const Integer*> (Context::getInstance()->getCurrentStack()->getConstant(0));
        const Integer* i2 = dynamic_cast<const Integer*> (Context::getInstance()->getCurrentStack()->getConstant(1));
        if ((i1 == 0 || i2 == 0)) return "Mod only with Integers";
        return "";
    }

    Mod* Mod::clone() const {
        return new Mod(_name);
    }

    const Number* Mod::apply(const Number* n1, const Number* n2) const throw (ArithmeticException) {
        const Integer* integer = dynamic_cast<const Integer*> (n2);
        const Integer* argument = dynamic_cast<const Integer*> (n1);
        if ((argument == 0 || integer == 0)) throw ArithmeticException("Mod only with Integers");
        Integer* e1 = new Integer(*integer);
        *e1 %= *argument;
        return e1;

    }
}